<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CommodityCategoryController extends Controller
{
    public function store(Request $request)
    {
        $category = Category::create(
            $request->only(['name', 'sort_id']),
            Category::find($request->get('parent_id', null)));

        return $this->response->created(null, $category->toArray());
    }

    public function list(Request $request)
    {
        return $this->response->array(
            Category::defaultOrder()
                ->get()
                ->toTree()
                ->toArray()
        );
    }

    public function delete($id)
    {
        try {
            DB::transaction(function () use ($id) {
                Category::query()->findOrFail($id)->delete();
            });
        } catch (\Exception $e) {
            $this->response->errorBadRequest($e->getMessage());
        }

        return $this->response->noContent();
    }

    public function update(Request $request, $id)
    {
        $category = Category::find($id);
        $category->update([
            'name' => $request->get('name', $category->name),
            'sort_id' => $request->get('sort_id', $category->sort_id),
        ]);

        return $this->response->created(null, $category->toArray());
    }
}
